<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\api\model;

use think\Model;
use think\helper\Hash;
use app\user\model\Role as RoleModel;
use think\Db;
use think\Session;
/**
 * 后台用户模型
 * @package app\admin\model
 */
class User extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'user';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
        /**
     * 用户登录
     * @param string $mobile 用户名
     * @param string $password 密码
     * @author 蔡伟明 <314013107@qq.com>
     * @return bool|mixed
     */
    public function logins($mobile = '', $password = '', $rememberme = false)
    {
        $mobile = trim($mobile);
        $password = trim($password);
        $map['status'] = 1;
        $map['mobile'] = $mobile;

        // 查找用户
        $user = db::name('user')->where($map)->find();
       
        if (!$user) {
            return 1;
        } else {
            // 检查是否分配用户组
            if ($user['role'] == 0) {
                return 2;
            }
			 $role = explode(',',$user['role']);
            $count = count($role);
			if($count == 1){
                $where[] = ['id','=',$user['role']];
            }else{
                $where[] = ['id','in',$role];
            }
            $where[] = ['status','=',1];
            // 检查是可登录后台
            if (!RoleModel::where($where)->value('accessa')) {
                return 3;
            }
            if (!Hash::check((string)$password, $user['password'])) {
                return 4;
            } else {
                $uid = $user['id'];
                // 更新登录信息
                $user['last_login_time'] = request()->time();
                if (db::name('user')->where('id',$uid)->update($user)) {
                    // 自动登录
                    return $this->autoLogin($this::get($uid), $rememberme);
                } else {
                    // 更新登录信息失败
                    return 5;
                }
            }
        }
        return false;
    }

    /**
     * 自动登录
     * @param object $user 用户对象
     * @param bool $rememberme 是否记住登录，默认7天
     * @author 蔡伟明 <314013107@qq.com>
     * @return bool|int
     */
    public function autoLogin($user, $rememberme = false)
    {
        // 记录登录SESSION和COOKIES
        $auth = array(
            'id'             => $user->id,
            // 'group'           => $user->group,
            'role'            => $user->role,
            'hid'            => $user->hid,
            'role_name'       => Db::name('admin_role')->where('id', $user->role)->value('name'),
            'avatar'          => $user->avatar,
            'username'        => $user->username,
            'mobile'        => $user->mobile,
            'last_login_time' => $user->last_login_time,
            'last_login_ip'   => get_client_ip(1),
        );
        cache("user_auths_$user->id", $auth);
        cache("user_auth_signs_$user->id", data_auth_sign($auth));
        
        $role = cache("user_auths_$user->id.role");
        $roles = explode(',',$role);
            $counts = count($roles);
            if($counts == 1){
                if($role == 1){
                    return 7;
                }
            }
            // 保存用户节点权限
          if ($counts != 1) {
            $where[] = ['id','in',$role];
            $menu_auth = Db::name('admin_role')->where($where)->where('hid',cache("user_auths_$user->id.hid"))->column('menu_auth');
            if (!$menu_auth) {
                cache("user_auths_$user->id", null);
                cache("user_auth_signs_$user->id", null);
                return 6;
            }
            $count = count($menu_auth);
            if($count != 1){
                $newArr = [];
                for ($i=0; $i <$count; $i++) { 
                    if(empty($newArr)){
                        $menu_auth[$i] = ltrim($menu_auth[$i],'[');
                        $menu_auth[$i] = rtrim($menu_auth[$i],']');
                        $newArr = $menu_auth[$i];
                    }else{
                        $menu_auth[$i] = ltrim($menu_auth[$i],'[');
                        $menu_auth[$i] = rtrim($menu_auth[$i],']');
                        // $newArr = array_merge((array)$menu_auth[$i],(array)$newArr);
                        $newArr = $newArr . "," . $menu_auth[$i];
                    }
                }
                $menu_auth = $newArr;
                if(is_string($menu_auth)){
                    $menu_auth = '[' . $menu_auth . ']';
                }
            }else{
                $menu_auth = $menu_auth[0];
            }
            // print_r($menu_auth);die;
            $menu_auth = json_decode($menu_auth, true);
        }
        // 记住登录
        if ($rememberme) {
            $signin_token = $user->username.$user->id.$user->last_login_time;
            cookie('uid', $user->id, 24 * 3600 * 100);
            cookie('signin_token', data_auth_sign($signin_token), 24 * 3600 * 100);
        }
        return 7;
    }
}
